package fi.foyt.cs.oauth;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.restlet.data.CacheDirective;
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.ext.freemarker.ContextTemplateLoader;
import org.restlet.ext.freemarker.TemplateRepresentation;
import org.restlet.representation.EmptyRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;

import fi.foyt.cs.Settings;
import fi.foyt.cs.api.APIResource;
import freemarker.template.Configuration;

public class LoginPageResource extends APIResource {

  @Get("html")
  public Representation representation() {
    String loginMethod = getQuery().getFirstValue("method");
    if (StringUtils.isBlank(loginMethod)) {
      return getPage("auth/login.html");
    } else {
      LoginMethod method = LoginMethod.valueOf(loginMethod);
      if (method == null) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Unknown login method " + loginMethod);
      }
      
      switch (method.getType()) {
        case OpenId:
          Reference targetUri = null;
          
          switch (method) {
            case Google:
              targetUri = new Reference(getRootRef() + "/openid_login?ax_required=email&ax_required=firstname&ax_required=lastname");
              targetUri.addQueryParameter("openid_identifier", "https://www.google.com/accounts/o8/id");
            break;
            case Yahoo:
              targetUri = new Reference(getRootRef() + "/openid_login?ax_required=email&ax_required=fullname");
              targetUri.addQueryParameter("openid_identifier", "https://me.yahoo.com");
            break;
          }
          
          redirectTemporary(targetUri);

        break;
        case Facebook:
          redirectTemporary(new Reference(getRootRef() + "/facebook_login"));
        break;
      }
    }
    
    return new EmptyRepresentation();
  }

  protected Representation getPage(String authPage) {
    Configuration config = new Configuration();
    ContextTemplateLoader ctl = new ContextTemplateLoader(getContext(), Settings.getServerUrl());
    config.setTemplateLoader(ctl);
    config.setLocale(getLocale());
    
    TemplateRepresentation result = new TemplateRepresentation(authPage, config, MediaType.TEXT_HTML);

    HashMap<String, Object> data = new HashMap<String, Object>();
    result.setDataModel(data);

    List<CacheDirective> noCache = new ArrayList<CacheDirective>();
    noCache.add(CacheDirective.noCache());
    getResponse().setCacheDirectives(noCache);
    
    return result;
  }
}
